package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class MemberController {
    @Autowired
    JedisPool jedisPool;
    @Reference
    MemberService memberService;
    /**
     * 登陆功能
     * @param map   登陆信息,手机号,验证码
     * @param response  response对象
     * @return      登陆结果flag
     */
    @RequestMapping("/check")
    public Result check(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        //loginInfo.telephone
        //loginInfo.validateCode
        try {
            String tel = (String) map.get("telephone");
            String validateCode = (String) map.get("validateCode");
            String validateCodeInRedis = jedisPool.getResource().get(tel+ RedisMessageConstant.SENDTYPE_LOGIN);
            if (validateCodeInRedis != null && validateCodeInRedis.equals(validateCode)) {
                Member member=memberService.findByTel(tel);
                if (member==null){
                    member=new Member();
                    member.setPhoneNumber(tel);
                    member.setRegTime(new Date());
                    memberService.addMember(member);
                }
                ObjectMapper json = new ObjectMapper();
                String memberJson = json.writeValueAsString(member);
                jedisPool.getResource().setex(tel,1800,memberJson);
                Cookie cookie = new Cookie("telephone",tel);
                response.addCookie(cookie);
                return new Result(true, MessageConstant.LOGIN_SUCCESS);
            }
            return new Result(false,MessageConstant.LOGIN_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.LOGIN_FAIL);
        }
    }
}
